/**
 * http 工具
 * @file
 * @date 2019-02-22 14:17:26
 */

layui.extend({
    oms_api_config: '{/}/static/js/module/api/zmn.api.config'
}).define(['$http', 'oms_api_config'], function (exports) {
    var $ = layui.$;
    var $http = layui.$http;
    var config = layui.oms_api_config || [];

    function _stringToCamelCase (str){
        var reg= /^([A-Za-z])([A-Za-z]*)/g;

        return str.replace(reg, function (match, p1, p2) {
            return p1.toUpperCase() + p2;
        });
    }

    function _normalizeParams (defaultParams, params) {
        var data = Object.assign({}, defaultParams, params);

        var newParams = {};

        Object.keys(data).forEach(function (key) {
            if (data[key] != null) {
                newParams[key] = data[key];
            }
        });

        return newParams;
    }

    var $api = {};

    Object.keys(config).forEach(function (key) {
        var apis = config[key];

        apis.forEach(function (api) {
            var type = api.type.toLowerCase();
            var loading = api.loading !== false;
            var apiName = key + _stringToCamelCase(api.name);
            var httpFn;

            if (type === 'get') {
                httpFn = loading ? $http.get :  $http.$get;
            } else if (type === 'post') {
                httpFn = loading ? $http.save :  $http.$save;
            }

            $api[apiName] = function (params) {
                var data = _normalizeParams(api.params, params);
                return httpFn(api.url, data);
            };
        });
    });

    exports('$api', $api);
});